<template>
    <view class="container">
        <header-nav :config="config" @tabChange="tabChange" @rightClick="rightClick"></header-nav>
        <search-bar :placeholderText="placeholderText" @searchFn="searchFn" :actions="actions" @actionFn="scan">
        </search-bar>
        <tab-bar :tabs="items" @clickTab="clickTab" :tabIndex="tabIndex"></tab-bar>

        <!-- 数据列表 -->
        <swiper
            v-if="reload"
            class="swiper product-main-list"
            :style="{ height: listHeight }"
            :current="tabIndex"
            @change="swiperChange">
            <swiper-item v-for="(swiperItem, swiperIndex) in items" :key="swiperIndex" >
                <pendingList ref="pendingList" :height="listHeight" v-if="tabIndex == 0"></pendingList>
                <order-list
                    v-else
                    :i="swiperIndex"
                    :index="tabIndex"
                    ref="mescrollItem"
                    :height="listHeight"
                    :sublistHeight="sublistHeight"
                    :state="swiperItem.state"
                    :init-data="initData"
                    :title="swiperItem.title"
                    :params="params"
                    :currentIndex="tabIndex"
                    :repositoryId="repositoryIds[swiperIndex]"
                    @showTel="openPopup"
                    @changeFn="openPop">
                </order-list>
            </swiper-item>
        </swiper>

        <!-- 联系电话弹窗 -->
        <uni-popup ref="centerPopup" :mask-click="true" @maskClick="canclePopup">
            <view class="toast">
                <view class="toast-type">选择联系人</view>
                <view class="toast-msg">
                    <view class="toast-tel" @click="makePhoneCall(linkPhone)">
                        仓库联系方式：{{ linkPhone || "暂无" }}
                    </view>
                    <view class="toast-tel" @click="makePhoneCall(storeLinkPhone)">
                        门店联系方式：{{ storeLinkPhone || "暂无" }}
                    </view>
                </view>
            </view>
        </uni-popup>

        <!-- 门店列表 -->
        <uni-popup ref="rightPopup" class="pop-box" :mask-click="true" @maskClick="">
            <depository-list
                :config="popConfig"
                :liheight="fullHeight"
                @chooseDepository="chooseDepository"
                @onBack="onBack"
                :state="state">
            </depository-list>
        </uni-popup>
		<uni-popup ref="tip" type="dialog" class="tip-box">
			<uni-popup-dialog type="text" title="温馨提示" :before-close="false" @close="save" 
				@confirm="save">
				<view>该客户还有{{otherList.length}}单待配送；</view>
				<scroll-view scroll-y style="max-height: 40vh;">
					<view v-for="item in otherList">订单号：{{item.orderNumber}}</view>
				</scroll-view>
			</uni-popup-dialog>
		</uni-popup>
    </view>
</template>

<script>
import headerNav from "../../components/header-nav.vue"
import searchBar from "@/components/common/search-bar.vue"
import tabBar from "@/pages_tms/components/common/tab-bar.vue"
import noticeBar from "@/pages_tms/components/order/notice-bar.vue"
import taskCard from "@/pages_tms/components/order/task-card.vue"
import orderList from "@/pages_tms/components/order/order-list.vue"
import depositoryList from "@/pages_tms/components/order/depository-list.vue"
import { getLocation } from "@/uni-sub-base/utils/mapUtil.js"
import { OrderInfoByNumber, OrderHandle, OrderDelivery } from "@/pages_tms/service/logistics.js"
import storage from "@/uni-sub-base/utils/storage.js"
import pendingList from "@/pages_tms/components/order/pending-list.vue"
export default {
    components: {
        headerNav,
        searchBar,
        tabBar,
        noticeBar,
        taskCard,
        orderList,
        depositoryList,
        pendingList,
    },
    data() {
        return {
            // config: {
            // 	title: '任务中心',
            // 	centerSlot: true,
            // 	backPage: '/pages/index/index',

            // },
            config: {
                backPage: "/pages/index/index",
                centerSlot: true,
                rightSlot: false,
                color: ["#333333"],
                statusBarFontColor: "#ffffff",
                rightBtns: [],
                tabs: [
                    {
                        title: "配送", // tppe 2
                    },
                    // {
                    //     title: "接单", // tppe 3
                    // },
                ],
            },
            popConfig: {
                title: "请选择仓库",
                color: "#333333",
                backgroundColor: [1, "#ffffff"],
                isCustomBackFn: true,
            },
            placeholderText: "请输入单号、手机号",
            actions: [
                {
                    isImgIcon: true,
                    type: "/static/icon/icon_search_bar_scan.png",
                    id: 1,
                },
            ],
            upOption: {
                use: false,
                auto: false,
            },
            downOption: {
                auto: false,
            },
            topHeight: uni.upx2px(272),
            items: [
                {
                    title: "接单",
                    state: 0,
                },
                {
                    title: "待取货",
                    state: 1,
                },
                {
                    title: "待配送",
                    state: 2,
                },
                {
                    title: "配送中",
                    state: 3,
                },
                {
                    title: "已送达",
                    state: 4,
                },
            ],
            tabIndex: 0,
            params: {},
            initData: false,
            repositoryId: 0,
            listHeight: "", //list所需高度
            sublistHeight: "", //list所需高度 待配送下面有按钮
            repositoryIds: [0, 0, 0, 0],
            fullHeight: 0,

            // 联系电话
            storeLinkPhone: 0,
            linkPhone: 0,
            state: 0,
            reload: false,
			otherList:[]
        }
    },
    watch: {
        tabIndex(i) {
            // 当列表禁止滚动时,需把列表滚动条置顶 (解决问题: "全部"tab翻到第二页,切换到其他tab,滚动到顶部,再切回"全部"tab,此时的列表数据应该重头开始)
            if (this.disableScroll) {
                this.disableScroll = false // 当disableScroll=true时,scroll-view的scrollTo会失效,需先开启,再置顶
                this.$nextTick(() => {
                    let mescroll = this.getMescroll(i)
                    mescroll && mescroll.scrollTo(0, 0)
                    setTimeout(() => {
                        // 经测试android真机需延时300ms才能恢复禁止滚动,否则scrollTo有可能无效
                        this.disableScroll = true
                    }, 300)
                })
            }
            this.state = i + 1
            // if (i == 1 || i == 3) {
            // 	this.actions = []
            // } else {
            // 	this.actions = [{
            // 		isImgIcon: true,
            // 		type: '/static/icon/icon_search_bar_scan.png',
            // 		id: 1
            // 	}]
            // }
        },
    },
    onShow() {
        this.reload = false
        this.$nextTick(() => {
            this.reload = true
        })
    },
    onReady() {
        plus.navigator.setStatusBarStyle("dark") // light（白色）、dark（黑色）
    },
    onLoad(e) {
        // 需要固定swiper的高度 (需减去悬浮tabs的高度64rpx)
        if (e.index) {
            this.tabIndex = Number(e.index)
            // console.log(typeof(this.tabIndex))
        }
        if (e && e.state && e.state != "undefined") {
            this.clickTab(Number(e.state) - 1)
        }
        this.listHeight =
            uni.getSystemInfoSync().windowHeight - this.topHeight - uni.getSystemInfoSync().statusBarHeight + "px"
        this.sublistHeight =
            uni.getSystemInfoSync().windowHeight - this.topHeight - uni.getSystemInfoSync().statusBarHeight - 60 + "px"
        getLocation(
            (res) => {
                console.log(res)
                this.params.location = res.longitude + "," + res.latitude
            },
            (error) => {
                console.log(this)
                console.log(error)
            },
        )
    },
    created() {
        let mainColor = this.easyGetColor("white")
        this.config.backgroundColor = [1, mainColor]
    },
    methods: {
        tabChange(e) {
            if (e == 0) {
                return
            } else if (e == 1) {
                this.easyGoTo("/pages_tms/packet/order/pendingOrder")
            }
        },
        // 获取指定下标的mescroll对象
        getMescroll(i) {
            let mescrollItems = this.$refs.mescrollItem
            if (mescrollItems) {
                let item = mescrollItems[i]
                if (item) return item.mescroll
            }
            return null
        },
        swiperChange(e) {
            let tabIndex = e.detail.current
            this.clickTab(tabIndex)
        },
        searchFn(key) {
            this.params.searchKey = key
            this.initData = !this.initData
            // let mescroll = this.getMescroll(this.tabIndex)
            // mescroll.resetUpScroll()
        },
        //tab切换
        clickTab(index) {
            if (this.tabIndex != index) {
                this.tabIndex = index
            }
        },
        // 页面的滚动事件
        onPageScroll(e) {
            this.disableScroll = Math.ceil(e.scrollTop) < this.topHeight
        },
        openPopup(data) {
            // console.log(data)
            this.storeLinkPhone = data.storeLinkPhone
            this.linkPhone = data.linkPhone
            this.setNoScroll()
            this.$refs.centerPopup.open("center")
        },
        canclePopup() {
            this.setScroll()
            this.$refs.centerPopup.close()
        },
        scan() {
            const that = this
            //扫一扫
            // console.log(123)
            //#ifdef APP-PLUS
            // 允许从相机和相册扫码

            uni.scanCode({
                success: function (res) {
                    let number = res.result
                    uni.showLoading({
                        title: "操作中",
                    })
                    // OrderInfoByNumber(number).then(res => {
                    // 	if (res.State == 1) {
                    // 		if (res.Data && res.Data.status == 1) { //取货操作
                    // 			let param = {}
                    // 			param.ids = res.Data.id
                    // 			param.operateType = res.Data.status
                    // 			param.location =that.params.location
                    // 			OrderHandle(param).then(res => {
                    // 				if (res.State == 1) {
                    // 					uni.hideLoading()
                    // 					that.easyToast("取货成功")
                    // 				} else {
                    // 					uni.hideLoading()
                    // 					that.easyToast(res.Msg)
                    // 				}
                    // 			})
                    // 		} else if (res.Data && res.Data.status == 3) { //跳转详情
                    // 			uni.hideLoading()
                    // 			that.easyGoTo("/pages_tms/packet/order/detail?id=" + res.Data.id)
                    // 		} else {
                    // 			uni.hideLoading()
                    // 			that.easyToast("当前订单状态不支持扫码操作")
                    // 		}
                    // 	} else {
                    // 		uni.hideLoading()
                    // 		that.easyToast(res.Msg)
                    // 	}
                    // })
                    OrderInfoByNumber(number).then((res) => {
                    	if (res.Data && res.State == 1) {
                    		if (res.Data.automaticPick == 1) {
                    			//接单操作
                    			let deliveryId = storage.getCache("deliveryId")
                    			if (!deliveryId) {
                    				this.easyToast("请先完善车辆信息")
                    				return
                    			}
                    			let param = {
                    				orderId: res.Data.id,
                    				deliveryId: deliveryId,
                    			}
                    			OrderDelivery(param).then((rsp) => {
                    				if (rsp.State == 1) {
                    					uni.showToast({
                    						title: "操作成功",
                    						icon: "none",
                    						duration: 1200,
                    					})
                    					if(res.Data.otherList && res.Data.otherList.length >0){
                    						this.otherList = res.Data.otherList
                    						this.$refs.tip.open()
                    					}else{
                    						setTimeout((e) => {
                    							that.scan()
                    						}, 1500)
                    					}
                    					
                    				} else {
                    					this.easyToast(rsp.Msg)
                    				}
                    			})
                    		} else if(res.Data.automaticPick == 2){
                    		   //跳转配送详情
                    		   uni.hideLoading()
                    		   that.easyGoTo("/pages_tms/packet/order/detail?id=" + res.Data.id)
                    		}else{
                    			//跳转接单详情
                    			uni.hideLoading()
                    			that.easyGoTo("/pages_tms/packet/order/sanDetail?id=" + res.Data.id)
                    		}
                    	} else {
                    		uni.hideLoading()
                    		that.easyToast(res.Msg)
                    	}
                    })
                },
                fail: function (err) {
                    that.easyToast(err)
                },
            })
            //#endif
            //#ifndef APP-PLUS
			uni.showLoading({
			    title: "操作中",
			})
            // that.easyToast("请在app中使用扫码功能")
			let number = '100FHTZ241218176'
			OrderInfoByNumber(number).then((res) => {
				if (res.Data && res.State == 1) {
					if (res.Data.automaticPick == 1) {
						//接单操作
						let deliveryId = storage.getCache("deliveryId")
						if (!deliveryId) {
							this.easyToast("请先完善车辆信息")
							return
						}
						let param = {
							orderId: res.Data.id,
							deliveryId: deliveryId,
						}
						OrderDelivery(param).then((rsp) => {
							if (rsp.State == 1) {
								uni.showToast({
									title: "操作成功",
									icon: "none",
									duration: 1200,
								})
								if(res.Data.otherList && res.Data.otherList.length >0){
									this.otherList = res.Data.otherList
									this.$refs.tip.open()
								}else{
									setTimeout((e) => {
										that.scan()
									}, 1500)
								}
								
							} else {
								this.easyToast(rsp.Msg)
							}
						})
					} else if(res.Data.automaticPick == 2){
					   //跳转配送详情
					   uni.hideLoading()
					   that.easyGoTo("/pages_tms/packet/order/detail?id=" + res.Data.id)
					}else{
						//跳转接单详情
						uni.hideLoading()
						that.easyGoTo("/pages_tms/packet/order/sanDetail?id=" + res.Data.id)
					}
				} else {
					uni.hideLoading()
					that.easyToast(res.Msg)
				}
			})
            //#endif
        },
		save() {
			this.$refs.tip.close()
			setTimeout((e) => {
				this.scan()
			}, 1500)
		},
        chooseDepository(id) {
            this.setScroll()
            console.log(id)
            this.repositoryIds[this.tabIndex] = Number(id)
            console.log(this.repositoryIds)
            // this.initData = !this.initData
            this.$forceUpdate()
            this.$nextTick(() => {
                let mescroll = this.getMescroll(this.tabIndex)
                mescroll.resetUpScroll()
            })
            this.$refs.rightPopup.close()
            // 这里要切换仓库
        },

        onBack() {
            this.setScroll()
            this.$refs.rightPopup.close()
        },

        openPop(state) {
            const _this = this
            _this.state = state
            uni.getSystemInfo({
                success(res) {
                    _this.fullHeight = res.windowHeight - uni.upx2px(88) + "px"
                    console.log(_this.fullHeight)
                    _this.setNoScroll()
                    _this.$refs.rightPopup.open("right")
                },
            })
        },
    },
}
</script>

<style lang="scss">
.page {
    padding: $app-page-padding;
    position: relative;

    .header-bg {
        position: absolute;
        left: 0;
        top: 0;
        right: 0;
        height: 250rpx;
        background: $color-white;
        border-bottom-left-radius: 50rpx;
        border-bottom-right-radius: 50rpx;
        z-index: 0;
    }
}

.main {
    position: relative;
    z-index: 1;
}

.sticky-tabs {
    z-index: 10;
    position: sticky;
    top: 88rpx;
    background-color: #fff;
}
/deep/.tip-box .uni-dialog-content{
	display: inherit;
}
</style>
